package com.tbgov.service;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.tbgov.config.SftpConfig;
import com.tbgov.util.BaseUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.function.Function;

/**
 * @author 1st
 */
@Service
@RequiredArgsConstructor
public class SftpUploadService {

    final SftpConfig config;

    public String uploadFile(MultipartFile file) {
        return operatorFile((sftp) -> {
            // 上传文件
            try (InputStream is = file.getInputStream()) {
                String fileName = "img/" + BaseUtil.buildFileName(file);
                String remoteFilePath = config.getUploadDirectory() + "/" + fileName;
                // String remoteFilePath = config.getUploadDirectory() + "/" + file.getOriginalFilename();
                sftp.put(is, remoteFilePath);
                return fileName;
            } catch (Exception e) {
                throw new IllegalArgumentException("Failed to upload file: " + e.getMessage());
            }
        });
    }

    public void deleteFile(String fileName) {
        if(StringUtils.isNotBlank(fileName)) {
            operatorFile((sftp) -> {
                // 删除文件
                try {
                    String remoteFilePath = config.getUploadDirectory() + "/" + fileName;
                    sftp.rm(remoteFilePath);
                    return remoteFilePath;
                } catch (SftpException e) {
                    throw new IllegalArgumentException("Failed to delete file: " + e.getMessage());
                }
            });
        }
    }

    public String operatorFile(Function<ChannelSftp, String> fun) {
        Session session = null;
        ChannelSftp channelSftp = null;
        try {
            // 设置JSch配置
            JSch jsch = new JSch();
            session = jsch.getSession(config.getUsername(), config.getHost(), config.getPort());
            session.setPassword(config.getPassword());
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();
            // 打开SFTP通道
            channelSftp = (ChannelSftp) session.openChannel("sftp");
            channelSftp.connect();
            return fun.apply(channelSftp);
        } catch (Exception e) {
            throw new IllegalArgumentException(e.getMessage());
        } finally {
            if (channelSftp != null && channelSftp.isConnected()) {
                channelSftp.disconnect();
            }
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }

}
